package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.result.ServiceCallResponse;
import com.cskaoyan.mall.commons.result.ServiceCallResponseUtil;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.OrderCancelDto;
import com.cskaoyan.order.dto.OrderItemDto;
import com.cskaoyan.order.service.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class PayOrderServiceImpl implements PayOrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;


    @Override
    public ServiceCallResponse paySuccess(String orderId) {
        // 修改订单状态
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        Order order = new Order();
        order.setPaymentType(1);
        order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
        order.setUpdateTime(new Date());
        order.setPaymentTime(new Date());
        int update = orderMapper.updateByExampleSelective(order, example);

        //修改订单详情对应的状态
        List<OrderCancelDto> itemsByOrderId = orderItemMapper.getItemsByOrderId(orderId);
        Example example1 = new Example(OrderItem.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId", orderId);
        OrderItem orderItem = new OrderItem();
        orderItem.setStatus(OrderConstants.ORDER_ITEM_STATUS_DEDUCTION_SUCCESS);
        int update1 = orderItemMapper.updateByExampleSelective(orderItem, example1);

        // 修改订单商品对应lock_count
        for (OrderCancelDto orderCancelDto : itemsByOrderId) {
            Stock stock = new Stock();
            stock.setStockCount(Long.valueOf(0));
            stock.setLockCount(-orderCancelDto.getNum());
            stock.setItemId(orderCancelDto.getItem_Id());
            stockMapper.updateStock(stock);
        }

        //TODO 需要修改
        return new ServiceCallResponseUtil<>().ok("success");
    }
}
